import React, { useRef, useEffect, useCallback } from 'react';
import router from "umi/router";
import { connect } from "dva";
import IframeWrapper from 'components/IframeWrapper';
import { Icon, Modal, NavBar, Toast } from 'antd-mobile';
import { getFormTitleKeyList } from 'utils/formilyAppHelperUtil';
import { sendToParent, openNotificationWithIconPhone } from "utils/comm";


const { operation } = Modal;

const containerStyle = {
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
};

const PhoneForm = (props) => {
  const { taskformFields, formLog, fieldData: logFieldData, location, dispatch } = props;
  const { query: { taskId, editable: editableParam } } = location;
  const editable = `${editableParam}` === '1';
  const countRef = useRef(0);
  const draftFieldDataRef = useRef(null);
  const getContentWindowRef = useRef(null);

  const sendToChild = useCallback((msg) => {
    if (getContentWindowRef.current) {
      getContentWindowRef.current().postMessage(msg, window.origin);
    }
  }, []);

  const setPhoneFormData = ({ datas }) => {
    if (editable) {
      if (datas) {
        draftFieldDataRef.current = datas.fieldData;
      }
    }
    countRef.current += 1;
    if (countRef.current === 2) {
      let fieldData;
      let formConfig;
      if (editable) {
        fieldData = draftFieldDataRef.current;
        formConfig = taskformFields;
      } else {
        fieldData = logFieldData;
        formConfig = formLog;
      }
      Toast.hide();
      sendToChild({
        type: 'formConfig',
        data: fieldData,
        setting: {
          editable,
          formConfig,
        },
      });
    }
  }

  useEffect(() => {
    Toast.loading('加载中', 0);
    dispatch({
      type: !editable ? "FlowHandle/getFormLog" : "FlowHandle/getTaskform",
      payload: { taskId },
    }).then(setPhoneFormData);
  }, [])

  const onSubmit = useCallback((payload, isDraft) => {
    if (!editable) return;
    let type = 'FlowHandle/handleTask';
    let hint = '任务处理';
    if (isDraft) {
      type = 'FlowHandle/handleDraft';
      hint = '暂存';
    }
    dispatch({
      type,
      payload,
    }).then(({ errCode, errMsg }) => {
      Toast.hide();
      if (errCode !== 0) {
        openNotificationWithIconPhone("error", errMsg || `${hint}失败`);
      } else {
        openNotificationWithIconPhone("success", `${hint}成功`);
        sendToParent({
          ...payload,
          lables: getFormTitleKeyList(formLog),
          schema: formLog,
        }, '*');
        router.goBack();
      }
    });
  }, [dispatch, editable, formLog]);

  return (
    <div style={containerStyle}>
      <NavBar
        mode="light"
        icon={<Icon type="left" />}
        onLeftClick={() => router.goBack()}
        rightContent={editable ? [(
          <Icon
            type="ellipsis"
            key="1"
            onClick={() => {
              operation([
                { text: '暂存', onPress: () => {
                  Toast.loading('加载中', 0);
                  sendToChild({ type: 'saveDraft' });
                }},
                { text: '处理', onPress: () => {
                  Toast.loading('加载中', 0);
                  sendToChild({ type: 'saveForm' });
                }},
              ]);
            }}
          />
        )] : []}
      >
        { editable ? '处理' : '表单日志' }
      </NavBar>
      <IframeWrapper
        autoFitHeight
        src="/flow-phone/form"
        style={{ flex: 1}}
        iframeStyle={{ height: '100%'}}
        messageHandlers={[
          (msg) => {
            if (msg.type === 'ready'){
              setPhoneFormData({});
            }
            if (msg.type === 'submitForm' || msg.type === 'submitDraft'){
              onSubmit({
                taskId,
                variables: msg.data,
              }, msg.type === 'submitDraft');
            }
          },
        ]}
        getContentWindow={getWindow => { getContentWindowRef.current  = getWindow; }}
      />
    </div>
  );
}

export default connect(({ FlowHandle = {}, loading }) => ({
  formLog: FlowHandle.formLog,
  taskformFields: FlowHandle.taskformFields,
  fieldData: FlowHandle.fieldData,
  loading,
}))(PhoneForm);
